//
//  AudioPlayer.m
//  XiMaLaYaFM
//
//  Created by MJL on 15/10/16.
//  Copyright (c) 2015年 马金丽. All rights reserved.
//

#import "AudioPlayer.h"
#import <AVFoundation/AVFoundation.h>
static AudioPlayer *share = nil;

@interface AudioPlayer ()
{
    BOOL _isPrepare;
}

@property(nonatomic,strong)AVPlayer *player;

@end

@implementation AudioPlayer


#pragma mark 重写初始化(int)方法
- (instancetype)init
{
    if (self = [super init]) {
        //注册通知中心
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playEndAction:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
    return self;
}

/**
 *  创建单例
 */

+ (instancetype)sharedInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        share = [[AudioPlayer alloc]init];
    });
    return share;
}
//准备播放的网址
- (void)prepareWithUrl:(NSString *)strinfUrl
{
    //创建item
    AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:[NSURL    URLWithString:strinfUrl]];
    //释放观察者
    if (self.player.currentItem) {
        [self.player.currentItem removeObserver:self forKeyPath:@"status"];
    }
    
    //添加观察者
    [item  addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    //根据当前item切换音乐
    [self.player replaceCurrentItemWithPlayerItem:item];
}
//播放
- (void)play
{
    if (!_isPrepare) {
        return;
    }
    [self.player play];
    _isPlaying = YES;
    //判断计时器是否存在
    if (self.timer) {
        return;
    }
    
    //初始化计时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timeAction:) userInfo:nil repeats:YES];
    
}
//暂停
- (void)pause
{
    if (!_isPlaying) {
        return;
    }
    [self.player pause];
    _isPlaying = NO;
    //销毁定时器
    [self.timer invalidate];
    self.timer = nil;
    
}
//停止
- (void)stop
{
    if (!_isPlaying) {
        return;
    }
    //先暂停
    [self pause];
    //把事件设置为0秒
    [self.player seekToTime:CMTimeMake(0, self.player.currentTime.timescale)];
    
}
//从指定时间开始播放
- (void)seekToTime:(float)time
{
    [self pause];
    //设置开始播放事件
   [self.player seekToTime:CMTimeMakeWithSeconds(time, self.player.currentTime.timescale) completionHandler:^(BOOL finished) {
       [self play];
   }];
}


#pragma mark 定时器的方法
- (void)timeAction:(NSTimer *)sender
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(playWithPlayer:withProgress:)]) {
        CGFloat progress = self.player.currentTime.value / self.player.currentTime.timescale;
        [self.delegate playWithPlayer:self withProgress:progress];
    }
}

#pragma mark 通知中心的方法
-(void)playEndAction:(NSNotification *)sender
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(playEndFinish:)]) {
        [self.delegate playEndFinish:self];
    }
}

#pragma mark 实现观察者的方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerStatus status = [change[@"new"] integerValue];
        switch (status) {
            case AVPlayerStatusFailed:{
                NSLog(@"失败");
                break;
            }
            case AVPlayerStatusReadyToPlay:{
                NSLog(@"准备好播放");
                _isPrepare = YES;
                [self play];
                break;
            }
            case AVPlayerStatusUnknown:{
                NSLog(@"未知");
                break;
            }
                
            default:
                break;
        }
    }
}

#pragma mark 懒加载
- (AVPlayer *)player
{
    if (!_player) {
        _player = [[AVPlayer alloc]init];
    }
    return _player;
}

- (void)dealloc
{
    //移除通知中心
    [[NSNotificationCenter defaultCenter]removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}



@end
